package com.backend.mzyf.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class ValidateCsrfFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        String token = null;
        String sessionToken = null;
        token = request.getParameter("csrf");
        sessionToken = (String) request.getSession().getAttribute("csrf");
        request.getSession().setAttribute("csrf",null);

        if (token != null && token.equals(sessionToken)){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            servletRequest.getRequestDispatcher("/csrfforbidden").forward(servletRequest, servletResponse);
        }
    }

    public void destroy() {

    }
}
